package tools.biback

import ch.qos.logback.classic.Level
import ch.qos.logback.classic.spi.LoggingEvent
import ch.qos.logback.classic.{Logger => ALogger}
import com.typesafe.scalalogging.{CanLog, LazyLogging, Logger}
import org.slf4j.MDC
import org.slf4j.Marker

object TryLogging extends App with LazyLogging {
  logger.debug("This is very convenient ;-)")
  logger.whenDebugEnabled {
    println("This would only execute when the debug level is enabled.")
  }
  new Try1()
  val alog = logger.underlying.asInstanceOf[ALogger]
  val e  = new LoggingEvent(ALogger.FQCN, alog, null, "a logging event {}",
    null, Array[Object]("ddd"))
  e.setLevel(Level.INFO)
  alog.callAppenders(e)
  Thread.sleep(5 * 1000L)
  alog.callAppenders(e)
}

object DummyMarker extends Marker {
  def add(childMarker: Marker): Unit = { println(childMarker) }
  def contains(childName: String): Boolean = false
  def contains(child: Marker): Boolean = false
  def getName: String = "DummyMarker"
  def hasChildren: Boolean = false
  def hasReferences: Boolean = false
  def iterator(): java.util.Iterator[Marker] = new java.util.Iterator[Marker] {
    def hasNext: Boolean = false
    def next(): Marker = throw new NoSuchElementException()
    override def remove(): Unit = throw new NoSuchElementException()
  }
  def remove(child: Marker): Boolean = false
}

class Try1() {
  case class CorrelationId(value: String)
  implicit case object CanLogCorrelationId extends CanLog[CorrelationId] {
    override def logMessage(originalMsg: String, a: CorrelationId): String = {
      println(a)
      MDC.put("correlationId", a.value)
      originalMsg
    }

    override def afterLog(a: CorrelationId): Unit = {
      println("x")
      MDC.remove("correlationId")
    }
  }

  implicit val correlationId = CorrelationId("ID")

  val logger = Logger.takingImplicit[CorrelationId]("test")
  def serviceMethod(implicit correlationId: CorrelationId): Unit = {
    logger.error(DummyMarker, "hi")
    logger.trace(s"Received value ${1+1} from db")
  }
  serviceMethod
}